
import Head from 'next/head'

<Head>
  <script>
    {
      `(function() {
         var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?e60fb290e204e04c5cb6f79b0ac1e697";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
       })();`
    }
  </script>
</Head>

![LangChain](https://pica.zhimg.com/50/v2-56e8bbb52aa271012541c1fe1ceb11a2_r.gif)



自定义MRKL代理
============================

本文档介绍如何创建自己的自定义MRKL Agent。

MRKL Agent由三个部分组成：

- 工具：代理可用的工具。
- LLMChain：生成以一定方式解析的文本，以确定要采取哪个动作。
- 代理类本身：解析LLMChain的输出，以确定要采取哪个动作。

本文档介绍如何通过创建自定义LLMChain来创建自定义MRKL代理。

自定义LLMChain（Custom LLMChain）[#](#Custom-LLMChain)
----

创建自定义代理的第一种方法是使用现有的代理类，但使用自定义LLMCain。

这是创建自定义代理的最简单方法。

强烈建议您使用 `ZeroShotAgent` ，因为目前这是最通用的一个。

创建自定义LLMCain的大部分工作都归结为提示符。因为我们使用的是一个现有的代理类来解析输出，所以提示符中要生成该格式的文本是非常重要的。此外，我们目前需要一个 agent_scratchpad 输入变量来记录以前的操作和观察结果。

这几乎总是提示符的最后一部分。

但是，除了这些说明之外，您还可以根据需要自定义提示。

为了确保提示符包含适当的指令，我们将在该类上使用`helper`方法。


`ZeroShotAgent` 的`helper`方法接受以下参数：

* tools：座席将有权访问的工具列表，用于设置提示的格式。
* prefix:要放在工具列表前面的字符串。
* suffix: 放在工具列表后面的字符串。
* input_variables：最后提示所期望的输入变量列表。


在这个练习中，我们将给予我们的代理访问Google搜索，我们将定制它，我们将让它回答为盗版。

```python
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain import OpenAI, SerpAPIWrapper, LLMChain
```

```python
search = SerpAPIWrapper()
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    )
]
```
```python
prefix = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:"""
suffix = """Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args"

Question: {input}
{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(
    tools, 
    prefix=prefix, 
    suffix=suffix, 
    input_variables=["input", "agent_scratchpad"]
)
```
如果我们感到好奇，我们现在可以看看最终的提示模板，看看它看起来像当它的所有放在一起。

```python
print(prompt.template)
``` 

```python
Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:

Search: useful for when you need to answer questions about current events

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Search]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args"

Question: {input}
{agent_scratchpad}

```

请注意，我们能够为代理提供自定义的提示模板，即不限于由 `create_prompt` 函数生成的提示，假设它满足代理的要求。

例如，对于 ZeroShotAgent ，我们需要确保它满足以下要求。

应该有一个以“Action：”开头的字符串和一个以“Action Input：”开头的字符串，并且两者都应该用换行符分隔。

```python
llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)
```

```python
tool_names = [tool.name for tool in tools]
agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)
```

```python
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
```

```python
agent_executor.run("How many people live in canada as of 2023?")
```

```python
> Entering new AgentExecutor chain...
Thought: I need to find out the population of Canada
Action: Search
Action Input: Population of Canada 2023
Observation: The current population of Canada is 38,661,927 as of Sunday, April 16, 2023, based on Worldometer elaboration of the latest United Nations data.
Thought: I now know the final answer
Final Answer: Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!

> Finished chain.
```

```python
"Arrr, Canada be havin' 38,661,927 people livin' there as of 2023!"
```

多路输入 (Multiple inputs)
---
代理还可以处理需要多个输入的提示。

```python
prefix = """Answer the following questions as best you can. You have access to the following tools:"""
suffix = """When answering, you MUST speak in the following language: {language}.

Question: {input}
{agent_scratchpad}"""

prompt = ZeroShotAgent.create_prompt(
    tools, 
    prefix=prefix, 
    suffix=suffix, 
    input_variables=["input", "language", "agent_scratchpad"]
)
```

```python
llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)
```

```python
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools)
```

```python
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
```

```python
agent_executor.run(input="How many people live in canada as of 2023?", language="italian")
```

```python
> Entering new AgentExecutor chain...
Thought: I should look for recent population estimates.
Action: Search
Action Input: Canada population 2023
Observation: 39,566,248
Thought: I should double check this number.
Action: Search
Action Input: Canada population estimates 2023
Observation: Canada's population was estimated at 39,566,248 on January 1, 2023, after a record population growth of 1,050,110 people from January 1, 2022, to January 1, 2023.
Thought: I now know the final answer.
Final Answer: La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.

> Finished chain.
```

```python
'La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.'
```




